package com.neusoft.nep.GridOfficer.controller;

import com.neusoft.nep.GridOfficer.entity.Officer;
import com.neusoft.nep.common.AlertUtils;
import com.neusoft.nep.common.FileUtils;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class GirdOfficerLoginViewController {
    static public String officerName;
    @FXML
    private TextField textField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Button btn_login;

    public static String getOfficerName() {
        return officerName;
    }

    public static void setOfficerName(String officerName) {
        GirdOfficerLoginViewController.officerName = officerName;
    }

    @FXML
    public void initialize() {
        Officer o1 = new Officer("001", "130", "李宁", "辽宁省", "大连市", "111");
        Officer o2 = new Officer("002", "131", "阿迪", "辽宁省", "沈阳市", "222");
        Officer o3 = new Officer("003", "132", "耐克", "吉林省", "长春市", "333");

        //从文件中读取网格员数据
        Map<String, Officer> officerMap = new HashMap<>();

        //初始化网格员数据
        officerMap.put(o1.getPhoneNumber(), o1);
        officerMap.put(o2.getPhoneNumber(), o2);
        officerMap.put(o3.getPhoneNumber(), o3);
        //将新注册用户写入文件
        FileUtils.writeMapObject("GirdOfficer.txt", officerMap);
    }

    public void login() throws IOException {
        //读取对象数据

        Map<String, Officer> officerMap = FileUtils.readMapObject("GirdOfficer.txt");
        //判断用户是不是存在的
        String phoneNumber = textField.getText();
        String password = passwordField.getText();
        if (officerMap.containsKey(phoneNumber)) {
            Officer o = officerMap.get(phoneNumber);
            officerName = officerMap.get(o.getPhoneNumber()).getName();
            if (password.equals(o.getPassword())) {
                AlertUtils.showDialog("用户登录", "登陆成功");
                //登陆成功跳转到管理员页面
                FXMLLoader fxmlLoader = new FXMLLoader();
                URL url = getClass().getResource("/com/neusoft/nep/GridOfficer/view/GridOfficerFeedBackListView.fxml");
                fxmlLoader.setLocation(url);
                Parent root = fxmlLoader.load();
                Scene scene = btn_login.getScene();
                scene.setRoot(root);
                Stage stage = (Stage) scene.getWindow();
                stage.show();
            } else {
                AlertUtils.showDialog("用户登录", "密码错误");
            }
        } else {
            AlertUtils.showDialog("用户登录", "该账号不存在");
        }


    }


}